<template>
  <div>
    <!-- 添加 -->
    <el-button size="small" @click="toAddHandler">添加</el-button>

    <!-- 表格 -->
    <el-table :data="roles" style="width: 100%" size="small">
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <span @click="deleteHandler(scope.row.id)">移除</span>
          <span @click="setHandler(scope.row)">授权</span>
          <span @click="editHandler(scope.row)">修改</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 模态框 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      {{ form }}
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.name" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveHandler">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 授权模态框 -->
    <el-dialog title="授权" :visible.sync="setDialogVisible" width="50%" :before-close="handleClose">
      {{ setForm }}
      <el-form ref="setForm" :model="setForm" label-width="80px">
        <el-form-item label="角色名称">
          {{ setRoleName }}
        </el-form-item>
        <el-form-item label="权限">
          <el-cascader-panel v-model="setForm.privileges" :options="privilege" :props="{ multiple: true, children: 'children', label: 'name', value: 'id'}" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSetHandler">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import qs from 'qs'
import { mapActions, mapState } from 'vuex'
export default {
  data() {
    return {
      title: '',
      dialogVisible: false,
      form: {},
      setRoleName: '',
      setDialogVisible: false,
      setForm: {},
      privilege: []
    }
  },
  computed: {
    ...mapState('role', ['roles']),
    ...mapState('user',['name'])
  },
  created() {
    this.findAllRoles()
    this.findAllPrivilieges()
  },
  methods: {
    ...mapActions('role', ['findAllRoles']),
    // 查询所有权限
    findAllPrivilieges() {
      console.log(this.request)
      this.request.get('/privilege/findPrivilegeTree').then(res => {
        // this.privilege = res.data
        // 调用递归方法，去除级联数据后将数据赋值给级联选择器
        this.privilege = this.getTreeData(res.data)
      })
    },
    // 递归方法
    getTreeData(data) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children)
        }
      }
      return data
    },
    // 确认授权
    saveSetHandler() {
      this.setForm.privileges = this.setForm.privileges.map(item => {
        console.log(item)
        return item[1]
      }).toString()
      request.post('/role/authorization', qs.stringify(this.setForm)).then(res => {
        this.setDialogVisible = false
        this.findAllPrivilieges()
        this.findAllRoles()
      })
    },
    // 授权
    setHandler(row) {
      this.setDialogVisible = true
      this.setRoleName = row.name
      row.privileges = row.privileges.map((item) => {
        const arr = new Map()
        // 将数据处理成数组的样子
        arr.set(item.parentId, item.id)
        // 再转换为数组
        return Array.from(arr)[0]
      })
      this.setForm = row
    },
    // 删除
    deleteHandler(id) {
      request.get('/role/deleteById', { params: { id }}).then(res => {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.findAllRoles()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      })
    },
    // 修改
    editHandler(row) {
      this.form = row
      this.dialogVisible = true
      this.title = '修改角色'
    },
    // 保存
    saveHandler() {
      request.post('/role/saveOrUpdate', qs.stringify(this.form)).then(res => {
        this.$message({
          message: res.message,
          type: 'success'
        })
        this.dialogVisible = false
        this.findAllRoles()
      })
    },
    // 添加
    toAddHandler() {
      this.dialogVisible = true
      this.title = '添加角色'
    },
    // 关闭添加模态框
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    }
  }
}
</script>

<style scoped>
    span {
        margin-right: .3rem;
        cursor: pointer;
    }
</style>
